﻿using Dapper;
using SassModule.Contracts;
using SassModule.Entity;
using SassModule.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SassModule.Services
{
    /// <summary>
    /// 菜单服务
    /// </summary>
    public class MenuService : IMenuService
    {
        /// <summary>
        /// 根据用户id返回菜单列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dbStr"></param>
        /// <returns></returns>
        public IEnumerable<string> Index(Guid userId, string dbStr = null)
        {
            using var db = SassModule.ConnCache.GetConn();
            StringBuilder sql = new StringBuilder();
            //验证是否是管理员
            sql.AppendLine("SELECT Id FROM Sys_Sass WHERE Id=@id");
            var exist= db.Query<Guid>(sql.ToString(), new { id = userId }).ToList();
            sql.Clear();
            if (exist.Count>0)
            {
                //如果是管理员
                if (userId == Guid.Parse(Util.ROOT))
                {
                    //如果是超级管理员
                    sql.AppendLine("SELECT  DISTINCT Path FROM Sys_Menu WHERE Path NOT LIKE '%/device/device-manager-user%'");
                }
                else
                {
                    sql.AppendLine("SELECT  DISTINCT Path FROM Sys_Menu WHERE Path NOT LIKE '%sass%' AND Path NOT LIKE '%/device/device-manager'");
                }
            }
            else
            {
                //如果是普通用户
                sql.AppendLine("SELECT DISTINCT	M.Path FROM Sys_Menu M ");
                sql.AppendLine("LEFT JOIN Sys_RoleMenu RM ON M.Id=RM.MId ");
                sql.AppendLine("LEFT JOIN Sys_UserRole UR ON RM.RId=UR.RId ");
                sql.AppendLine("WHERE UR.UId=@userId ");
            }
            return db.Query<string>(sql.ToString(), new { userId });
        }
        /// <summary>
        /// 返回账套下的菜单
        /// </summary>
        /// <param name="dbStr"></param>
        /// <returns></returns>
        public IEnumerable<string> Index(string dbStr = null)
        {
            using var db = SassModule.ConnCache.GetConn();
            var sasses = db.Query<Sass>("SELECT * FROM Sys_Sass WHERE DB=@dbStr", new { dbStr }).ToList();
            if (sasses.Count <= 0) return null;
            string sql = null;
            if (sasses[0].Id== Guid.Parse(Util.ROOT))
            {
                //返回sass相关的
                sql = "SELECT  DISTINCT Path FROM Sys_Menu WHERE Path NOT LIKE '%/device/device-manager-user%'";
            }
            else
            {
                //过滤掉sass相关的
                sql = "SELECT  DISTINCT Path FROM Sys_Menu WHERE Path NOT LIKE '%sass%' AND Path NOT LIKE '%/device/device-manager'";
            }
            return db.Query<string>(sql.ToString());
        }
    }
}
